import nedb from './nedb'

export default {
  /**
   * 设置任务
   * @param {Object} user 用户信息
   */
  async setTask (task) {
    try {
      var result = await nedb.task_list.find({_index: task._index || 0})
      if (result.length > 0) { // 已经存在了更新数据
        var a = await nedb.task_list.update({_index: task._index}, task)
        return Promise.resolve(a)
      } else { // 不存在添加数据
        var count = await nedb.task_list.count({})
        task.create_time = parseInt(Date.now())
        task._index = count + 1
        var b = await nedb.task_list.insert(task)
        return Promise.resolve(b)
      }
    } catch (e) {
      return Promise.resolve(null)
    }
  },
  /**
   * 获取用户
   * @param {Number} id 客服ID
   */
  async getTask (_index) {
    var result
    try {
      if (_index) {
        result = await nedb.task_list.find({_index: _index})
      } else {
        result = await nedb.task_list.find({})
      }
      return Promise.resolve(result)
    } catch (e) {
      return Promise.resolve([])
    }
  }
}
